import { AttrType } from "../../attr/AttrType";
import { BattleFormula } from "../../BattleFormula";
import { EventId } from "../../event/EventId";
import EventMgr from "../../event/EventMgr";
import { BattleRole } from "../../role/BattleRole";
import { DamageResult, ITriggerResult } from "../../trigger/const/ITriggerResult";
import { TriggerType } from "../../trigger/const/TriggerType";
import { MathUtil } from "../../util/MathUtil";
import { EffectBase } from "../EffectBase";

/**
 * 攻击伤害效果
 */
export class DamageEffect extends EffectBase {


    excute(args: { caster: BattleRole; target: BattleRole; results: ITriggerResult[]; }): void {
        let caster = args.caster;
        let target = args.target;
        let result: DamageResult = {
            resultType: "attackDamage",
            caster: caster,
            target: target,
            damage: 0,
            isHit: false,
            isCritial: false,
            isGeDang: false,
            isContinueAttack: false,
            isKill: false,
            xiXue: 0,
            fanShang: 0,
            damageIndex: this.effectData.params.damageIndex || 0,
        }
        let hitRate = BattleFormula.getHitRate(caster, target);
        let isHit = MathUtil.isHitRate(hitRate);
        result.isHit = isHit;
        //是否命中
        if (isHit) {
            let baseDamage = BattleFormula.getBaseDamage(caster, target, this.effectData.params.value);
            //是否暴击
            let cricialRate = BattleFormula.getCritialRate(caster, target);
            let isCricial = MathUtil.isHitRate(cricialRate);
            result.isCritial = isCricial;
            if (isCricial) {
                //暴击伤害
                baseDamage = BattleFormula.getCriticalDamage(baseDamage, caster, target);
            }
            //伤害加成
            baseDamage = BattleFormula.getDamageAdd(baseDamage, caster);
            //伤害减免
            baseDamage = BattleFormula.getDamageReduce(baseDamage, target);
            //吸血属性
            let xixue = BattleFormula.getXixue(baseDamage, caster);
            result.xiXue = xixue;
            //敌人反伤
            let fanshang = BattleFormula.getFanshang(baseDamage, caster);
            result.fanShang = fanshang;

            if (baseDamage >= target.attrMgr.getAttr(AttrType.hp)) {
                result.isKill = true;
            }
            target.attrMgr.updateAttr(AttrType.hp, -baseDamage);
            if (target.attrMgr.getAttr(AttrType.hp) <= 0) {
                result.isKill = true;
            }
            result.damage = baseDamage;
            caster.triggerMgr.trigger(TriggerType.hit, { caster: caster, target: target, results: [] });
        } else {
            //触发受击者身上闪避的效果(前端做表现也是根据触发做表现-比如伤害表现，在技能播到伤害帧时触发，闪避回血，在目标被攻击时触发表现)
            target.triggerMgr.trigger(TriggerType.dodge)
        }
        args.results.push(result)
        console.log("DamageEffect", result)
        //根据结果注册表现触发器
        EventMgr.ins.event(EventId.TRIGGER_RESULT, result)
    }
}